package cz.tomasdvorak.cars.auth;

import cz.tomasdvorak.cars.CarExpensesApp;
import cz.tomasdvorak.cars.dto.Role;
import cz.tomasdvorak.cars.dto.User;
import cz.tomasdvorak.cars.utils.Lists;
import org.apache.wicket.Request;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;

public class MyAuthenticatedWebSession extends AuthenticatedWebSession {

    private User user;

    public MyAuthenticatedWebSession(Request request) {
        super(request);
    }

    public boolean authenticate(String username, String password) {
        User user = ((CarExpensesApp) getApplication()).getUsersDao().authenticate(
                username, password);
        if(user != null) {
            this.user = user;
        }
        return user != null;
    }

    public Roles getRoles() {
        if(user != null) {
            if(Role.ADMIN.equals(user.getRole())) {
                return new Roles(Lists.array(Role.ADMIN.name(), Role.USER.name()));
            }
            return new Roles(user.getRole().name());
        }
        return null;
    }

    public User getUser() {
        return user;
    }
}
